<?php

namespace App\Controller;

use App\Model\Users;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

/**
 * @Controller(prefix="api/user")
 */
class UserController
{
    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(HttpResponse $response)
    {
        $this->response = $response;
    }

    /**
     * @GetMapping(path="all")
     */
    public function index(): ResponseInterface
    {
//        $users = Users::query()->get();
//
//        return $this->response->json([
//            'code'    => 0,
//            'message' => 'success',
//            'data'    => $users,
//        ]);
        //事务处理
        try {
            // 第二个数据库事务（直接查询）
            Db::connection('second')->beginTransaction();

//            $affected = Db::connection('second')
//                ->table('user_profiles')
//                ->where('user_id', $userId)
//                ->update(['updated_at' => date('Y-m-d H:i:s')]);
//
//            if ($affected === 0) {
//                throw new \RuntimeException('更新用户资料失败');
//            }

            $defaultDbData = Users::query()->get();

            $secondDbData = Db::connection('second')
                ->table('oc_user')
                ->get();

            Db::connection('second')->commit();

            return $this->response->json([
                'code'    => 0,
                'message' => 'success',
                'defaultData'    => $defaultDbData,
                'secondDbData'   => $secondDbData,
            ]);
        } catch (\Throwable $e) {
            Db::connection('second')->rollBack();
            throw $e;
        }
    }
}
